//
//  SearchKeyHistoryView.swift
//  MyTest
//
//  Created by guanzhongwang on 2021/5/16.
//

import UIKit

class SearchKeyHistoryView: UIView {
    var allClearBlock : (()->Void)?
    private let titleLabel = UILabel()
    private var arrow:UIImageView!
    private var open:Bool = false
    private let donebtn = UIButton(type: .custom)
    private var keys:Array<HistoryKeyView> = []
    private let btn = UIButton(type: .custom)

    init(items:Array<NewsSearchTextModel>) {
        super.init(frame: .zero)
        titleLabel.text = "搜索历史"
        titleLabel.textColor = B999_TITLE_COLOR
        titleLabel.font = Font_Size_14
        addSubview(titleLabel)
        titleLabel.isUserInteractionEnabled = true
        titleLabel.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(moreclick)))
        titleLabel.snp.makeConstraints({
            $0.left.top.equalTo(15)
        })
        arrow = UIImageView.init(image: UIImage(named: "xiaarrow")?.withRenderingMode(.alwaysTemplate))
        arrow.isUserInteractionEnabled = true
        arrow.addGestureRecognizer(UITapGestureRecognizer.init(target: self, action: #selector(moreclick)))
        arrow.tintColor = B999_TITLE_COLOR
        addSubview(arrow)
        arrow.snp.makeConstraints({
            $0.left.equalTo(titleLabel.snp.right).offset(2)
            $0.centerY.equalTo(titleLabel)
            $0.height.width.equalTo(12)
        })
        btn.font = Font_Size_12
        btn.setTitleColor(B999_TITLE_COLOR, for: .normal)
        btn.addTarget(self, action: #selector(clearTap(btn:)), for: .touchUpInside)
        btn.setImage(UIImage(named: "clear")?.withRenderingMode(.alwaysTemplate).reSizeImage(reSize: CGSize.init(width: 12, height: 12)), for: .normal)
        btn.setImage(UIImage(), for: .selected)
        btn.setTitle("完成", for: .selected)
        btn.tintColor = B999_TITLE_COLOR
        btn.contentEdgeInsets = UIEdgeInsets.init(top: 10, left: 15, bottom: 10, right: 15)
        addSubview(btn)
        btn.snp.makeConstraints({
            $0.centerY.equalTo(titleLabel)
            $0.right.equalToSuperview()
        })
        donebtn.isHidden = !btn.isSelected
        donebtn.contentEdgeInsets = UIEdgeInsets.init(top: 10, left: 15, bottom: 10, right: 15)
        donebtn.font = Font_Size_12
        donebtn.setTitleColor(B999_TITLE_COLOR, for: .normal)
        donebtn.addTarget(self, action: #selector(allClear), for: .touchUpInside)
        donebtn.setTitle("全部删除", for: .normal)
        addSubview(donebtn)
        donebtn.snp.makeConstraints({
            $0.centerY.equalTo(titleLabel)
            $0.right.equalTo(btn.snp.left)
        })

        self.setItems(items: items)
    }
    @objc private func allClear(){
        let alert = UIAlertController.init(title: "清空确认", message: "确认删除全部搜索历史？", preferredStyle: .alert)
        let cancel = UIAlertAction.init(title: "取消", style: .cancel)
        let out = UIAlertAction.init(title: "确定", style: .default) {[weak self] (al) in
            for v in (self!.keys){
                v.removeFromSuperview()
            }
            self?.keys.removeAll()
            self?.arrow.transform = CGAffineTransform(rotationAngle:0)
            self?.allClearBlock?()
        }
        alert.addAction(cancel)
        alert.addAction(out)
        self.fatherViewController()?.present(alert, animated: true, completion: {
            
        })
    }
    @objc private func clearTap(btn:UIButton){
        btn.isSelected = !btn.isSelected
        donebtn.isHidden = !btn.isSelected
        for v in keys {
            v.hiddenClose = donebtn.isHidden
        }
        self.updateKeys(hidden: donebtn.isHidden)
    }
    func setItems(items:Array<NewsSearchTextModel>) {
        for i in 0..<items.count {
            let key = HistoryKeyView(item: items[i], index: i)
            key.delegate = self
            addSubview(key)
            keys.append(key)
        }
        btn.isSelected = false
        donebtn.isHidden = !btn.isSelected
        for v in keys {
            v.hiddenClose = donebtn.isHidden
        }
        self.updateKeys(hidden: false)
        self.updateKeys(hidden: true)
    }
    private func updateKeys(hidden:Bool) {
        for v in keys {
            v.hiddenClose = true
            v.isHidden = true
            v.snp.removeConstraints()
        }
        var temp:UIView?
        var count = hidden ? 6:keys.count
        if count>keys.count {
            count = keys.count
        }
        for i in 0..<count {
            let key = keys[i]
            key.updateLayout(index: i)
            key.hiddenClose = donebtn.isHidden
            key.isHidden = false
            key.snp.remakeConstraints({
                if temp == nil {
                    $0.top.equalTo(titleLabel.snp.bottom).offset(15)
                    $0.left.equalTo(0)
                }else{
                    if i%2 == 0 {
                        $0.left.equalTo(0)
                        $0.top.equalTo((temp?.snp.bottom)!).offset(15)
                    }else{
                        $0.right.equalTo(0)
                        $0.top.equalTo((temp?.snp.top)!)
                    }
                }
                $0.width.equalToSuperview().dividedBy(2)
                if count - 1 == i {
                    $0.bottom.equalToSuperview().inset(15)
                }
            })
            temp = key
        }
        arrow.isHidden = keys.count>6 ? false : true
        arrow.transform = CGAffineTransform(rotationAngle: hidden ? 0:CGFloat.pi)

    }
    @objc private func moreclick(){
        guard keys.count>6 else {
            return
        }
        open = !open
        self.updateKeys(hidden: !open)
    }
    required init?(coder: NSCoder) {
        fatalError()
    }
}
extension SearchKeyHistoryView:HistoryKeyViewDelegate{
    func deleteKey(index: Int) {
        let key = keys[index]
        key.removeFromSuperview()
        keys.remove(at: index)
        self.updateKeys(hidden: false)
    }
}
